import json
import matplotlib.pyplot as plt
import pandas as pd
import sys

def convert_balance(balance):
  result = []
  
  for b in balance:
    item = {
      "timestamp": b["timestamp"],
      "total": b["total"],
    }
    result.append(item)

  return sorted(result, key=lambda x: x['timestamp'])

def convert_fills(fills):
  result = []
  
  for f in fills:
    item = {
      "timestamp": f["timestamp"],
      "signed_fill_qty": f["signed_fill_qty"],
      "usdt": f['fill_price'] * f['fill_qty']
    }
    result.append(item)

  return sorted(result, key=lambda x: x['timestamp'])

def unique_fills(fills):
  fill_id_set = set()
  result = []

  for f in fills:
    if f["fill_id"] not in fill_id_set:
      fill_id_set.add(f["fill_id"])
      result.append(f)

  return result

if __name__ == "__main__":
  balance_path = sys.argv[1]
  fills_path = sys.argv[2]

  with open(balance_path,"r") as f:
    balance = json.load(f)

  with open(fills_path,"r") as f:
    fills = json.load(f)

  uniqued_fills = unique_fills(fills)
  print("dup fills:" + str(len(fills) - len(uniqued_fills)))
  fills = uniqued_fills

  dka_balance = filter(lambda b : b["currency"] == "DKA", balance)

  converted_dka_balance = convert_balance(dka_balance)

  df = pd.DataFrame(converted_dka_balance)
  df.timestamp = pd.to_datetime(df.timestamp, unit='ns')

  plt.plot(df.timestamp, df.total, marker='.', label="dka balance")

  init_dka = df.total[0]
  end_dka = df.total[df.total.size - 1]

  usdt_balance = filter(lambda b : b["currency"] == "USDT", balance)

  converted_usdt_balance = convert_balance(usdt_balance)

  df = pd.DataFrame(converted_usdt_balance)
  df.timestamp = pd.to_datetime(df.timestamp, unit='ns')

  plt.plot(df.timestamp, df.total, marker='.', label="usdt balance")

  init_usdt = df.total[0]

  converted_fills = convert_fills(fills)

  df = pd.DataFrame(converted_fills)
  df.timestamp = pd.to_datetime(df.timestamp, unit='ns')

  dka = df.signed_fill_qty.cumsum() + init_dka
  fill_end_dka = dka.iloc[-1]
  plt.plot(df.timestamp, dka, marker='.', label="dka fills")
  usdt = df.usdt.cumsum() + init_usdt
  plt.plot(df.timestamp, usdt, marker='.', label="usdt fills")

  plt.title(fills[0]["exchange"] + "-" + fills[0]["owner"])

  print("exchange:", fills[0]["exchange"], "balance:", end_dka, "fills:", fill_end_dka, "diff:", end_dka - fill_end_dka)

  plt.legend()
  plt.savefig(balance_path + ".png")
  # plt.show()
